package com.googlecode.silicoin.gen;

import java.io.IOException;
import java.io.StringWriter;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class HBMRender {

	private Configuration templateconfig;

	public HBMRender() {
		this.initialize();
	}

	public void initialize() {
		try {
			if (templateconfig == null) {
				templateconfig = new Configuration();
				templateconfig
						.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
				templateconfig.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);
				templateconfig.setTemplateLoader(new ClassTemplateLoader(this
						.getClass(), "/"));
				templateconfig.setTemplateUpdateDelay(1200);
				templateconfig.setDefaultEncoding("UTF-8");
				templateconfig.setLocale(new java.util.Locale("zh_CN"));
				templateconfig.setNumberFormat("0.##########");
			}
		} catch (Exception e) {
		}
	}

	public String render(EntityDefinition entity, String templateName)
			throws TemplateException, IOException {
		StringWriter writer = new StringWriter();
		Template tl = templateconfig.getTemplate(templateName, templateconfig
				.getLocale());
		SimpleHash root = new SimpleHash();
		root.put("entity", entity);
		tl.process(root, writer);
		return writer.toString();
	}

	public String render(EntityDefinition entityDefinition)
			throws TemplateException, IOException {
		if (entityDefinition == null || entityDefinition.getClassName() == null
				|| entityDefinition.getSuperClassName() == null) {
			throw new java.lang.IllegalArgumentException(
					"wrong entityDefinition!");
		}

		String superClassName = entityDefinition.getSuperClassName();

		String templateName = superClassName.replace(".", "/") + ".ftl";
		StringWriter writer = new StringWriter();

		Template tl = templateconfig.getTemplate(templateName, templateconfig
				.getLocale());
		SimpleHash root = new SimpleHash();
		root.put("entity", entityDefinition);
		tl.process(root, writer);
		return writer.toString();
	}
}
